const fs = require('fs');
const path = require('path');
const DocxMerger = require("docx-merger");
const Docxtemplater = require("docxtemplater");
const PizZip = require("pizzip");
const { PDFDocument, rgb } = require('pdf-lib');
const mammoth = require("mammoth");

const getRandomArrayElements = function (arr, count) {
  if (arr.length < count) {
    count = arr.length;
  }
  let shuffled = arr.slice(0), i = arr.length, min = i - count, temp, index;  //只是声明变量的方式, 也可以分开写
  while (i-- > min) {
    index = Math.floor((i + 1) * Math.random()); //这里的+1 是因为上面i--的操作  所以要加回来
    temp = shuffled[index];  // 即值交换
    shuffled[index] = shuffled[i];
    shuffled[i] = temp;
  }
  return shuffled.slice(min);
};

const timeShow = function (useSeconds) {
  const hours = Math.floor(useSeconds / 60 / 60);
  let minutes = Math.floor((useSeconds / 60) % 60);
  let seconds = Math.floor(useSeconds % 60);
  minutes = minutes < 10 ? '0' + minutes : minutes;
  seconds = seconds < 10 ? '0' + seconds : seconds;
  let showTime = `${seconds}秒`;
  if (minutes) {
    showTime = `${minutes}分` + showTime
  }
  if (hours) {
    showTime = `${hours}时` + showTime
  }
  return showTime;
}


const shuffle = function shuffle(array) {
  var m = array.length,
    t, i;
  while (m) {
    i = Math.floor(Math.random() * m--);
    t = array[m];
    array[m] = array[i];
    array[i] = t;
  }
  return array;
}


const mkdirs = function (dirname, mode, callback) {
  fs.exists(dirname, function (exists) {
    if (exists) {
      callback();
    } else {
      console.log(path.dirname(dirname));
      mkdirs(path.dirname(dirname), mode, function () {
        fs.mkdir(dirname, mode, callback);
      });
    }
  });
}
//递归创建目录 同步方法
const mkdirsSync = function (dirname, mode) {
  console.log(dirname);
  if (fs.existsSync(dirname)) {
    return true;
  } else {
    if (mkdirsSync(path.dirname(dirname), mode)) {
      fs.mkdirSync(dirname, mode);
      return true;
    }
  }
}

// worker生成world文档
const createStudentWorld = (students) => {
  return new Promise((resolve, reject) => {
    const workerTemplateDistPath = path.join(__dirname, '../public/uploads', 'workerTemplate.docx');
    let content = fs.readFileSync(path.resolve(__dirname, workerTemplateDistPath), 'binary');
    students.forEach((student, index) => {
      let { name, idCard } = student;
      const fileDistPath = path.join(__dirname, "../public/templates/workerStudents", `${index+1}-worker-${name}.docx`);
      
      let zip = new PizZip(content);
      let doc = new Docxtemplater(zip);
      doc.setData({
        name,
        idCard,
        index: index+1
      });
      doc.render();
      var buf = doc.getZip().generate({ type: 'nodebuffer' });
      fs.writeFileSync(path.resolve(__dirname, fileDistPath), buf);
    });
    setTimeout(() => {
      resolve()
    }, 2000)
  }).catch(err => {
    throw new SystemErrException("worker生成world文档失败：" + error);
  })
}

module.exports = {
  getRandomArrayElements,
  shuffle,
  timeShow,
  mkdirs,
  mkdirsSync,
  createStudentWorld
};  